import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/image_response.dart';
import 'package:flutter_syt/generated/assets.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/image_picker_helper.dart';
import 'package:flutter_syt/utils/permission_helper.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/auto_image.dart';

import '../../global_easy_loading.dart';

class SubmissionFileUploadPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _SubmisstionFileUploadState();
  }
}

class _SubmisstionFileUploadState extends State<SubmissionFileUploadPage> {
  var filePaths = <PlatformFile>[];
  var choseMedias = <ChooseImageData>[];
  var fileUploadPaths = <ImageResponse>[];
  var mediaUploadPaths = <ImageResponse>[];

  late TextEditingController textController = new TextEditingController();
  late TextEditingController titleTextController = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(S.of(context).Volunte_contribution),
      ),
      body: GestureDetector(
          onTap: ClickUtils.debounce(() {
            FocusScope.of(context).requestFocus(FocusNode());
          }),
          child: ListView(
            children: [
              _titleFieldWidget(),
              if (filePaths.isNotEmpty) _filesWidget(),
              if (choseMedias.isNotEmpty) _mediaWidget(),
              Container(
                alignment: Alignment.center,
                child: TextButton(
                  child: Text(S.of(context).Select_file),
                  onPressed: ClickUtils.debounce(() {
                    _getSelectUploadTypePage();
                  }),
                ),
              ),
              _inputWidget(),
            ],
          )),
    );
  }

  void _getSelectUploadTypePage() async {
    FocusScope.of(context).requestFocus(FocusNode());
    if (choseMedias.length + filePaths.length == 5) {
      customShowToast(S.of(context).five_files);
      return;
    }
    await showDialog(
        context: context,
        builder: (builder) {
          return SimpleDialog(
            title: Text(S.of(context).Contribution),
            children: [
              SimpleDialogOption(
                onPressed: ClickUtils.debounce(() {
                  Navigator.pop(context);
                  _getFiles();
                }),
                child: Padding(
                  padding: EdgeInsets.symmetric(vertical: 6),
                  child: Text(S.of(context).contribution_Select_file),
                ),
              ),
              SimpleDialogOption(
                onPressed: ClickUtils.debounce(() {
                  Navigator.pop(context);
                  _getMedias();
                }),
                child: Padding(
                  padding: EdgeInsets.symmetric(vertical: 6),
                  child: Text(S.of(context).contribution_Select_Picture),
                ),
              ),
            ],
          );
        });
  }

  Widget _filesWidget() {
    return Container(
      child: Column(
        children: filePaths
            .map((e) => Container(
                  padding: EdgeInsets.all(15),
                  child: Row(
                    children: [
                      Expanded(
                          child: Text(
                        '${(e.path ?? "").split('/').last}',
                        style: TextStyle(color: Colors.green),
                      )),
                      // Spacer(),
                      SizedBox(width: 16),
                      TextButton(
                          onPressed: ClickUtils.debounce(() {
                            setState(() {
                              filePaths.remove(e);
                            });
                          }),
                          child: Text(S.of(context).del_title)),
                    ],
                  ),
                ))
            .toList(),
      ),
    );
  }

  Widget _mediaWidget() {
    return Container(
      child: Column(
        children: choseMedias
            .map((e) => Container(
                  padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
                  child: Row(
                    children: [
                      Expanded(
                        child: Text(
                          '${e.files.first.path.split('/').last}',
                          //style: TextStyle(color: Colors.red),
                          softWrap: true,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      // Spacer(),
                      SizedBox(width: 16),
                      TextButton(
                          style: ButtonStyle(
                              // backgroundColor: MaterialStateProperty.all(Colors.red),
                              ),
                          onPressed: ClickUtils.debounce(() {
                            setState(() {
                              choseMedias.remove(e);
                            });
                          }),
                          child: Text(S.of(context).del_title)),
                    ],
                  ),
                ))
            .toList(),
      ),
    );
  }

  static var _maxBytes = 40 * 1024 * 1024;
  void _getFiles() async {
    if (await PermissionHelper.checkPhotosPermission(context)) {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
          withData: true,
          type: FileType.custom,
          allowedExtensions: [
            'pdf',
            'doc',
            'docx',
            'xls',
            'xlsx',
            'mp3',
            'wav',
            'mp4',
            'avi',
            'txt',
            'mov'
          ]);
      if (result != null) {
        var paths = result.files;
        for (int i = 0; i < paths.length; i++) {
          var item = paths[i];
          if (item.size > _maxBytes) {
            customShowToast(S.of(context).file_max_hint);
            return;
          }
        }
        if (paths != null) {
          filePaths.addAll(paths);
          setState(() {});
        }
      }
    }
  }

  void _getMedias() async {
    var result = await ImageHelper.pickMutableImage(context);
    try {
      var path = result.files.first;
      var paths = choseMedias
          .map((e) => e.files.map((n) => n.path))
          .expand((element) => element)
          .toList();
      if (paths.contains(path) == false) {
        choseMedias.add(result);
        setState(() {});
      }
    } catch (e) {}
  }

  Widget _titleFieldWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: ClickUtils.debounce(() {
        FocusScope.of(context).requestFocus(FocusNode());
      }),
      child: Container(
        padding: EdgeInsets.all(10),
        child: TextField(
          enableInteractiveSelection: true,
          maxLength: 100,
          inputFormatters: [
            FilteringTextInputFormatter.deny(appContext.emojiRegexp)
          ],
          controller: titleTextController,
          decoration: InputDecoration(
            border: UnderlineInputBorder(
              borderSide: BorderSide(
                width: 0.5,
                color: Colors.red,
              ),
            ),
            hintText: S.of(context).submission_title,
            hintStyle: TextStyle(
              color: ThemeColor.colorBlack40,
              fontSize: 16,
            ),
          ),
        ),
      ),
    );
  }

  Widget _inputWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: ClickUtils.debounce(() {
        FocusScope.of(context).requestFocus(FocusNode());
      }),
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.all(10),
            child: TextField(
              enableInteractiveSelection: true,
              inputFormatters: [
                FilteringTextInputFormatter.deny(appContext.emojiRegexp)
              ],
              controller: textController,
              keyboardType: TextInputType.multiline,
              maxLines: 5,
              autofocus: false,
              decoration: InputDecoration(
                border: OutlineInputBorder(
                  borderSide: const BorderSide(
                    width: 0.5,
                    color: Color(0xFFE5E5E5),
                  ),
                  borderRadius: const BorderRadius.all(
                    Radius.circular(8.0),
                  ),
                ),
                hintText: S().submission_desc,
                hintStyle: TextStyle(
                  color: ThemeColor.colorBlack40,
                  fontSize: 16,
                ),
              ),
            ),
          ),
          Container(
            // margin: EdgeInsets.fromLTRB(0, 35.0, 0, 80.0),
            padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 15),
            child: ElevatedButton(
              child: Text(
                S.of(context).submit,
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              onPressed: ClickUtils.debounce(() {
                _submit();
              }),
            ),
          ),
        ],
      ),
    );
  }

  void _submit() async {
    if (titleTextController.text.isEmpty) {
      customShowToast(S.of(context).submission_title_hint);
      return;
    }

    if (textController.text.isEmpty &&
        (choseMedias.isEmpty && filePaths.isEmpty)) {
      customShowToast(S.of(context).submission_desc_hint);
      return;
    }

    EasyLoading.instance.loadingStyle = EasyLoadingStyle.light;
    EasyLoading.show(
      status: S.of(context).submitting,
      maskType: EasyLoadingMaskType.black,
      indicator: const AutoImage(
        Assets.loading,
        width: 64,
        height: 64,
      )
    );

    try {
      if (await uploadFile() == false) {
        return;
      }
      if (await uploadMedia() == false) {
        return;
      }
      var filePaths = fileUploadPaths.map((e) => e.url);
      var mediaPaths = mediaUploadPaths.map((e) => e.url);
      var resultPaths = [filePaths, mediaPaths]
          .expand((element) => element)
          .toList()
          .join(',');
      await API.shared.feedback.volunteerManuscript(
          titleTextController.text, textController.text, resultPaths);
      customShowSuccess(S.of(context).submit_success);
      EasyLoading.dismiss();
      Navigator.pop(context);
    } catch (e) {
      EasyLoading.dismiss();
      customShowError(S.of(context).submit_failed);
    }
  }

  /// 上传文件
  Future<bool> uploadFile() async {
    for (var data in filePaths) {
      var fileName = data.path?.split('/').last;
      var bytes = data.bytes;
      var path = data.path ?? "";
      if (fileName != null && bytes != null) {
        try {
          var result = await API.shared.common.uploadFile(fileName, path);
          fileUploadPaths.add(result);
        } catch (e) {
          await UtilsOther.showCustomShowError(e);
          // if (e is DioError) {
          //   customShowToast(e.message);
          // }
          fileUploadPaths.clear();
          return false;
        }
      } else {
        return false;
      }
    }
    return true;
  }

  /// 上传图片
  Future<bool> uploadMedia() async {
    for (var data in choseMedias) {
      try {
        var path = data.files.first.path;
        var result = await API.shared.common.uploadImage(path);
        mediaUploadPaths.add(result);
      } catch (e) {
        customShowToast("$e");
        mediaUploadPaths.clear();
        return false;
      }
    }
    return true;
  }
}
